<?php
// +----------------------------------------------------------------------
// | 志进科技
// +----------------------------------------------------------------------
// | 官方网站: http://www.zhijin101.com
// +----------------------------------------------------------------------
// | Author: 张亚伟 <1743325520@qq.com>
// +----------------------------------------------------------------------

namespace Api\Controller;
/**
 * 订单
 */
class OrderController extends ApiController
{
    protected $noCheck = ['return_goods', 'apply_return'];

    function _initialize() {
        parent::_initialize();
    }

    public function detail()
    {
        $id = I('id');
        $order = M('order')->where(['id'=>$id, 'user_id'=>$this->uid])->find();
        if(empty($order)){
            $this->ajaxReturn(['s'=>false, 'm'=>'订单不存在']);
        }
        $order_goods = M('order_info')->where(['code'=>$order['order']])->select();
        
    }

    /**
     * 可退款退货商品
     */
    public function return_goods()
    {
        $order_id = I('order_id');
        $refund_type = I('refund_type');

        $order = M('order')->where(['id'=>$order_id, 'user_id'=>$this->uid])->find();
        if(empty($order)){
            $this->ajaxReturn(['s'=>false, 'm'=>'订单不存在']);
        }
        $status_error = '';
        if($refund_type == 1){
            if(!$order['pay_status']){
                $status_error = '订单状态不符合申请退款';
            }
        }else if($refund_type == 2){
            if($order['wu_status'] == 0){
                $status_error = '订单状态不符合申请退货';
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'退款类型错误']);
        }
        if($status_error){
            $this->ajaxReturn(['s'=>false, 'm'=>$status_error]);
        }

        $returnModel = M('return');
        $rgModel = M('return_goods');
        $return_list = $rgModel->alias('rg')->join("__RETURN__ r ON rg.return_id=r.id", 'LEFT')->where(['r.order_id'=>$order_id, 'r.status'=>['not in', [3]]])->group('rg.oi_id')->getField('rg.oi_id,sum(rg.num) as return_num');
        $return_list = $return_list ? $return_list : [];

        $order_goods = M('order_info')->where(['code'=>$order['code']])->select();
        $can_return_goods = [];
        foreach ($order_goods as $key => &$og_item) {
            $og_item['return_max_num'] = $og_item['num'];

            $product = M('product')->where(array('id' => $og_item['pid']))->find();
            $product_attr = M('product_attr')->where(array('id' => $og_item['aid']))->find();
            $product['listimg'] = json_decode($product['listimg']);
            $og_item['listimg'] = $product['listimg'][0];
            $og_item['title'] = $product['title'];
            $og_item['attr'] = $product_attr['name'];
            $og_item['ds'] = $product['ds'];
            $og_item['price'] = $product_attr['dif']+$product['price'];

            if(isset($return_list[$og_item['id']])){
                $og_item['return_max_num'] = $og_item['return_max_num']-$return_list[$og_item['id']];
            }
            if($og_item['return_max_num'] < 1){
                unset($order_goods[$key]);
            }else{
                unset($og_item['code']);
                unset($og_item['aid']);
                $can_return_goods[] = $og_item;
            }
        }
        if(empty($can_return_goods)){
            $this->ajaxReturn(['s'=>false, 'm'=>'暂无可退款商品']);
        }

        $return_max_money = 0;
        if($order){
            $return_max_money = $order['cprice'];
            // 冻结金额
            $dj_return_money = $returnModel->where(['order_id'=>$order_id, 'status'=>['not in', [3]]])->sum('money');
            $dj_return_money = $dj_return_money ? $dj_return_money : 0;
            $return_max_money = $return_max_money-$dj_return_money;
            $return_max_money = $return_max_money > 0 ? $return_max_money : 0;
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'order'=>$order, 'can_return_goods'=>$can_return_goods, 'return_max_money'=>$return_max_money]);
    }

    /**
     * 提交退款信息
     */
    public function apply_return()
    {
        $order_id = I('order_id');
        $refund_type = I('refund_type');
        $reason = I('reason');
        $imgs = I('imgs');
        $money = I('money');

        $order = M('order')->where(['id'=>$order_id, 'user_id'=>$this->uid])->find();
        if(empty($order)){
            $this->ajaxReturn(['s'=>false, 'm'=>'订单不存在']);
        }
        $status_error = '';
        if($refund_type == 1){
            if(!$order['pay_status']){
                $status_error = '订单状态不符合申请退款';
            }
        }else if($refund_type == 2){
            if($order['wu_status'] == 0){
                $status_error = '订单状态不符合申请退货';
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'退款类型错误']);
        }
        if($status_error){
            $this->ajaxReturn(['s'=>false, 'm'=>$status_error]);
        }

        $returnModel = M('return');
        $rgModel = M('return_goods');
        $return_list = $rgModel->alias('rg')->join("__RETURN__ r ON rg.return_id=r.id", 'LEFT')->where(['r.order_id'=>$order_id, 'r.status'=>['not in', [3]]])->group('rg.oi_id')->getField('rg.oi_id,sum(rg.num) as return_num');
        $return_list = $return_list ? $return_list : [];

        $order_goods = M('order_info')->where(['code'=>$order['code']])->select();
        $can_return_goods = [];
        foreach ($order_goods as $key => &$og_item) {
            $og_item['return_max_num'] = $og_item['num'];

            $product = M('product')->where(array('id' => $og_item['pid']))->find();
            $product_attr = M('product_attr')->where(array('id' => $og_item['aid']))->find();
            $product['listimg'] = json_decode($product['listimg']);
            $og_item['listimg'] = $product['listimg'][0];
            $og_item['title'] = $product['title'];
            $og_item['attr'] = $product_attr['name'];
            $og_item['ds'] = $product['ds'];
            $og_item['price'] = $product_attr['dif']+$product['price'];

            if(isset($return_list[$og_item['id']])){
                $og_item['return_max_num'] = $og_item['return_max_num']-$return_list[$og_item['id']];
            }
            if($og_item['return_max_num'] < 1){
                unset($order_goods[$key]);
            }else{
                unset($og_item['code']);
                // unset($og_item['aid']);
                $can_return_goods[] = $og_item;
            }
        }
        if(empty($can_return_goods)){
            $this->ajaxReturn(['s'=>false, 'm'=>'暂无可退款商品']);
        }

        $return_max_money = 0;
        if($order){
            $return_max_money = $order['cprice'];
            // 冻结金额
            $dj_return_money = $returnModel->where(['order_id'=>$order_id, 'status'=>['not in', [3]]])->sum('money');
            $dj_return_money = $dj_return_money ? $dj_return_money : 0;
            $return_max_money = $return_max_money-$dj_return_money;
            $return_max_money = $return_max_money > 0 ? $return_max_money : 0;
        }
        if($money > 0){
            if($money > $return_max_money){
                $this->ajaxReturn(['s'=>false, 'm'=>'最多退款'.$return_max_money.'元']);
            }
        }

        $return_data = [
            'user_id'       => $this->uid,
            'order_id'      => $order['id'],
            'refund_no'     => 'R'.date('YmdHis').rand(10000, 99999),
            'order_no'      => $order['code'],
            'refund_type'   => $refund_type,
            'status'        => 1,
            'money'         => $money,
            'reason'        => $reason,
            'imgs'          => $imgs,
            'create_time'   => time(),
            'update_time'   => time(),
        ];
        $return_goods_data = [];
        foreach ($can_return_goods as $key => $crg) {
            $return_goods_data[] = [
                'order_id'      => $order['id'],
                'order_no'      => $order['code'],
                'oi_id'         => $crg['id'],
                'pid'           => $crg['pid'],
                'aid'           => $crg['aid'],
                'num'           => $crg['return_max_num'],
            ];
        }
        $returnModel->startTrans();
        $return_id = $returnModel->add($return_data);
        if(!$return_id){
            $returnModel->rollback();
            $this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
        }
        foreach ($return_goods_data as $key => &$rg) {
            $rg['return_id'] = $return_id;
        }
        $res = $rgModel->addAll($return_goods_data);
        if($res){
            $returnModel->commit();
            $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'return_id'=>$return_id]);
        }else{
            $returnModel->rollback();
            $this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
        }
    }

    public function return_info()
    {
        $return_id = I('return_id');
        $return = M('return')->where(['id'=>$return_id, 'user_id'=>$this->uid])->field('id,order_no,refund_type,status,money,create_time')->find();
        if(empty($return)){
            $this->ajaxReturn(['s'=>false, 'm'=>'失败，退货单不存在']);
        }
        $return['create_time'] = date('Y年m月d日', $return['create_time']);
        $return_goods = M('return_goods')->alias('rg')->join('__PRODUCT__ p ON rg.pid=p.id', 'LEFT')->join('__PRODUCT_ATTR__ pa ON rg.aid=pa.id', 'LEFT')->where(['rg.return_id'=>$return_id])->field('rg.*,p.title,listimg,p.price,pa.name as attr_name')->select();
        if($return_goods){
            foreach ($return_goods as $key => &$goods) {
                if($goods['listimg']){
                    $goods['listimg'] = json_decode($goods['listimg'], true);
                    if($goods['listimg']){
                        $goods['listimg'] = $goods['listimg'][0];
                    }
                }
            }
        }
        $return_address = yzl_config('product.return_address');
        
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'return'=>$return, 'return_address'=>$return_address , 'return_goods'=>$return_goods]);
    }

    /**
     * 退款物流
     */
    public function return_logistics()
    {
        $return_id = I('return_id');
        $logistics_name = I('logistics_name');
        $logistics_code = I('logistics_code');

        $return = M('return')->where(['id'=>$return_id, 'user_id'=>$this->uid])->find();
        if(empty($return)){
            $this->ajaxReturn(['s'=>false, 'm'=>'失败，退货单不存在']);
        }
        if($return['status'] == 4){
            $this->ajaxReturn(['s'=>false, 'm'=>'失败，已填写物流信息']);
        }
        if($return['status'] == 5){
            $this->ajaxReturn(['s'=>false, 'm'=>'失败，退款单已完成']);
        }
        if($return['status'] != 2){
            $this->ajaxReturn(['s'=>false, 'm'=>'失败，状态不正确']);
        }
        $data = [
            'logistics_name'    => $logistics_name,
            'logistics_code'    => $logistics_code,
            'logistics_time'    => time(),
            'status'            => 4,
            'update_time'       => time(),
        ];
        $res = M('return')->where(['id'=>$return_id])->save($data);
        if($res){
            $this->ajaxReturn(['s'=>true, 'm'=>'ok']);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'失败']);
        }
    }
}